<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Services\ListService;
use App\Http\Controllers\Api\V1\Frontend\Service\IndexController;

class ServerModelShow
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if (method_exists($response,'getData')) {
            $responseData = $response->getData();

            if ($responseData->status ?? '' == 'success' && !empty($responseData->data) && is_array($responseData->data)) {
                $responseData = json_decode(json_encode($responseData),true);

                if ($request->path() == 'api/frontend/service/details' && $request->filled('id')) {

                    $request->offsetSet('server_id',$request->input('id'));
                }

                $responseData['module'] = (new IndexController())->getNodeShowModule($request);

                $response->setData($responseData);
            }
        }

        return $response;
    }
}
